<template>
    <div class="table-box">
        <ProTable ref="proTable" title="用户列表" :columns="columns" :request-api="getTableList" :init-param="initParam"
            :data-callback="dataCallback">
            <!-- 表格 header 按钮 -->
            <template #tableHeader="scope">
                <el-button type="primary" class="standard-btn" :icon="CirclePlus" @click="openDiolg('新增', null)">
                    新增用户
                </el-button>
                <el-button type="info" plain icon="Upload"
                    @click="() => { ExcelRef.open('/staff/socialfund/importSocFee') }"
                    v-hasPermi="['system:user:import']">导入</el-button>
                <el-button type="warning" plain icon="Download" @click="handleExport"
                    v-hasPermi="['system:user:export']">导出</el-button>

            </template>
            <!-- 表格操作 -->
            <template #operation="scope">
                <el-button type="primary" link :icon="View" @click="openDiolg('查看', scope.row)">
                    查看
                </el-button>
                <el-button type="primary" link :icon="EditPen" @click="openDiolg('编辑', scope.row)">
                    编辑
                </el-button>
                <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">
                    删除
                </el-button>
            </template>
        </ProTable>
        <ExcelUpload ref="ExcelRef" title="导入demo" type="1" :templateParams="templateParams">
        </ExcelUpload>
    </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, getCurrentInstance, toRefs } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, tabBarProps } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import {
    ColumnProps,
} from "@/components/ProTable/interface";
import {
    CirclePlus,
    Delete,
    EditPen,
    Download,
    Upload,
    View,
    Refresh,
} from "@element-plus/icons-vue";
import {
    deviceNumList,
    devTypeList,
    devOnlineStatusList,
    devUseStatusList,
    findLabel,
} from "@/utils/stata";
import { getDicts } from "@/api/system/dict/data";
import { useHandleData } from "@/hooks/useHandleData";
const proxy = getCurrentInstance()?.proxy;
const emit = defineEmits(["changeItem"]);
const { sys_user_sex } = toRefs<any>(proxy?.useDict("sys_user_sex"));
const router = useRouter();
const ExcelRef = ref(null);
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<any>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
    return {
        list: [
            {
                username: "12",
                devBrand: 0,
                sex: 0,
                userImg: [],
                createTime: "2023-10-10 10:10:10",
                longString: "舟行数日，到得武穴，已是湖北境内。这晚到了福池口，舟子泊了船，准拟过夜，俞莲舟忽听得岸上马嘶声响，向舱外一张，只见两骑马刚好掉转马头，向镇上驰去。"
            },
            {
                username: "12",
                devBrand: 0,
                sex: 1,
                userImg: ['https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg', 'https://picsum.photos/400/400',],
                createTime: "2023-10-10 10:10:10",
                longString: "舟行数日，到得武穴，已是湖北境内。这晚到了福池口，舟子泊了船，准拟过夜，俞莲舟忽听得岸上马嘶声响，向舱外一张，只见两骑马刚好掉转马头，向镇上驰去。"
            },
        ],
        total: 15,
        pageNum: 1,
        pageSize: 10,
    };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
    //   let newParams = JSON.parse(JSON.stringify(params));
    //   newParams.createTime && (newParams.startTime = newParams.createTime[0]);
    //   newParams.createTime && (newParams.endTime = newParams.createTime[1]);
    //   delete newParams.createTime;
    //   return getUserList(newParams);
    return PromiseDel;
};
const templateParams = {
    templateName: "demo模板",
    templateUrl: "system/user/importTemplate",
    templateType: 0,
    templateObj: {}
}

// 表格配置项
const columns: any = [
    { type: "index", label: "序号", width: 80 },
    //1.普通输入框
    {
        prop: "username",
        label: "用户姓名",
        search: { el: "input" },
        width: 100
    },
    //2.下拉框 自定义下拉选项类型
    {
        prop: "devBrand",
        label: "设备品牌",
        search: { el: "select" },
        enum: deviceNumList,
        render: (scope) => {
            let devBrand = findLabel(scope.row.devBrand, "deviceNumList");
            return devBrand;
        },
        width: 150
    },
    //下拉框 数据源从字典中拿
    {
        prop: "sex",
        label: "用户性别",
        search: { el: "select" },
        enum: () => {
            return getDicts("sys_user_sex");
        },
        fieldNames: { label: "dictLabel", value: "dictValue" },
        render: (scope) => {
            let sex = proxy?.selectDictLabel(sys_user_sex.value, scope.row.sex);
            return sex;
            // return <>
            //        <dict-tag options={{ sys_user_sex.value }}  value={{ scope.row.sex }} />
            // </>
        },
        width: 100
    },
    //图片
    {
        prop: "userImg",
        label: "图片(无或有)",
        render: (scope: any) => {
            if (scope.row.userImg[0]) {
                return (
                    <el-image
                        class="table-img"
                        src={scope.row.userImg[0]}
                        zoom-rate={1.2}
                        max-scale={7}
                        min-scale={0.2}
                        preview-src-list={scope.row.userImg}
                        fit="cover"
                        preview-teleported
                    />
                )
            } else {
                return '暂无图片'
            }
        },
        width: 150
    },
    {
        prop: "longString",
        label: "长文字单行",
        search: { el: "input" },
    },
    {
        prop: "longString",
        label: "长文字多行",
        search: { el: "input" },
        showOverflowTooltip: false,
        render: (scope: any) => {
            return <>
                <el-tooltip
                    effect="dark"
                    content={scope.row.longString}
                    placement="top"
                >
                    <div class="table-ellipsis">
                        {scope.row.longString}
                    </div>
                </el-tooltip>

            </>
        },
    },
    // 日期连选
    {
        prop: "createTime",
        label: "创建时间",
        width: 180,
        search: {
            el: "date-picker",
            span: 2,
            props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" },
            //   defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"],
        },
    },
    { prop: "operation", label: "操作", fixed: "right", width: 240 },
];

// 删除用户信息
const deleteAccount = async (params: any) => {
    await useHandleData(PromiseDel, { id: [params.id] }, '是否删除编号为' + 1 + '的数据');
    proTable.value?.getTableList();
};
//模拟 调用接口
const PromiseDel = () => new Promise((resolve, reject) => resolve(true))

/** 导出按钮操作 */
function handleExport() {
    proxy.download("system/user/export", {

    }, `user_${new Date().getTime()}.xlsx`);
};

const openDiolg = (title: string, rowData: any) => {
    let params: any = {
        title,
        isView: title === "查看",
        rowData: { ...rowData },
        api: title === "新增" ? () => Promise.resolve(true) : title === "编辑" ? () => Promise.resolve(true) : undefined,
        getTableList: proTable.value?.getTableList,
    };
    emit("changeItem", "1", params, title);
};
</script>
